<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\command\service\MqttNewService;

class Mqtt extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('mqtt')
            ->setDescription('the mqtt command');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->subscribe();
    }

    //订阅消息
    protected function subscribe()
    {
        $server   = '127.0.0.1';
        $port     = 7788;
        $clientId = 'local_'. rand(1000000, 99999999);
        $topic    = "test-mqtt/#";
        $username = "admin";
        $pwd      = "123456";

        $mqtt = new MqttNewService($server, $port, $clientId);
        if(!$mqtt->connect(true, NULL, $username, $pwd)) {
           return "账号秘钥错误";
        }

        $mqtt->debug = true;

        $topics[$topic] = array('qos' => 0, 'function' => array($this,"procMsg"));
        $mqtt->subscribe($topics, 0);

        while($mqtt->proc()) {

        }

        $mqtt->close();
    }

    function procMsg($topic, $msg){
        $msg =$msg; // bin2hex($msg);
        echo $msg. "\n";
    }
}

